<?php 

class SMReceiverModel {
    private $config=array();
    private $db=null;
    private $content=null;

    public function __construct($post_array, $connector=null){
        $this->config = $this->extractVars($post_array);
        
        if(!$connector){
            trigger_error("no db connector provided", E_USER_ERROR);
        }else{
            $this->db = $connector;
        }
    }

    public function extractVars($post_array){
        $config = array();
        $content = base64_decode($post_array['content']);
        $unserialized_array = unserialize($content);

        $config['domain'] = $unserialized_array['transmitter_base_url'];
        $config['appkey'] = $unserialized_array['application_key'];
        $config['messages'] = $unserialized_array['messages'];

        return $config;
    }

    public function authenticateRequest(){
        if(!$this->authenticateDomain($this->config['domain']) || !$this->authenticateAppKey($this->config['appkey'])){
            error_log("SM_message: domain(".$this->config['domain'].") or appkey(".$this->config['appkey'].") does not authenticate");
            die(); // domain or application key does not authenticate; ignore request
        }
    }

    public function authenticateDomain($domain){
        $action = "SELECT * FROM domains WHERE domain_name='" . addslashes($domain) . "'";
        $result = $this->db->query($action);
        return mysql_num_rows($result);
    }

    public function authenticateAppKey($appkey){
        $action = "SELECT * FROM config WHERE appkey='" . addslashes($appkey) ."'";
        $result = $this->db->query($action);
        return mysql_num_rows($result);
    }

    public function storeMessage($message, $message_type, $domain, $message_file, $message_line, $php_self){
        $content = addslashes($message);
        $message_type = addslashes($message_type);
        $date_created = date("Y-m-d H:i:s");

        $action = "INSERT INTO messages (domain, message, message_file, message_line, message_type, php_self, date_created)
                VALUES ('$domain', '$content', '$message_file', $message_line, $message_type, '$php_self', '$date_created')";
        return $this->db->query($action);
    }

    public function storeMessages(){
        foreach($this->config['messages'] as $message){
            $this->storeMessage($message['message'], $message['message_type'], $this->config['domain'], 
                                $message['message_file'], $message['message_line'], $message['php_self']);
        }
    }

    public function sanitize(){
        $this->config['appkey'] = filter_var($this->config['appkey'], FILTER_SANITIZE_STRING);
        $this->config['domain'] = filter_var($this->config['domain'], FILTER_SANITIZE_URL);
        return $this->config;
    }
}

?>